package com.tanhua.server.service;

import com.aliyun.oss.OSSClient;
import com.tanhua.server.config.AliyunConfig;
import com.tanhua.server.vo.SoundUploadResult;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;

@Service
public class SoundUploadService {

    //允许上传的格式
    private static final String[] Sound_TYPE=new String[]{".m4a"};

    @Autowired
    private OSSClient ossClient;

    @Autowired
    private AliyunConfig aliyunConfig;

    public SoundUploadResult upload(MultipartFile uploadFile) {

        SoundUploadResult fileUploadResult = new SoundUploadResult();
        //对音频进行校验
        //是否合法
        boolean isLegal=false;

        for (String type : Sound_TYPE) {

            if(StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(),type)){
                isLegal=true;
                //匹配到了就跳出循环
                break;
            }
        }

        //格式错误,返回error
        if(!isLegal){
            fileUploadResult.setStatus("error");
            return fileUploadResult;
        }

        //文件新路径
        String fileName = uploadFile.getOriginalFilename();
        String filePath=getFilePath(fileName);

        //上传到阿里云
        try {
            ossClient.putObject(aliyunConfig.getBucketName(),filePath,new ByteArrayInputStream(uploadFile.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
            //上传失败
            fileUploadResult.setStatus("error");
            return fileUploadResult;
        }

        //上传成功
        fileUploadResult.setStatus("done");
        //文件名
        fileUploadResult.setName(aliyunConfig.getUrlPrefix()+filePath);
        //uid
        fileUploadResult.setUid(String.valueOf(System.currentTimeMillis()));
        return fileUploadResult;

    }


    /**
     * 上传的目录
     * 目录: 根据年月日归档
     * 文件名: 时间戳 + 随机数
     * @param sourceFileName
     * @return
     */
    private String getFilePath(String sourceFileName){
        DateTime dateTime = new DateTime();
        return "sounds/"+dateTime.toString("yyyy")
                +"/"+dateTime.toString("MM")+"/"
                +dateTime.toString("dd")+"/"+System.currentTimeMillis()+
                RandomUtils.nextInt(100,9999)+"."+
                StringUtils.substringAfterLast(sourceFileName,".");
    }
}